package com.tuling.limit;

/**
 * 令牌桶
 * 生成令牌的速度是恒定的，而请求去拿令牌是没有速度限制的。
 * 摘自：jianshu.com/p/d9504fc0af4d
 * <p>
 * Created by chenhs on 2018/7/2.
 */
public class TokenBucketDemo {

    private static long time = System.currentTimeMillis();
    private static int createTokenRate = 45;
    private static int size = 10;
    //当前令牌数
    private static int tokens = 0;

    public static boolean grant() {
        long now = System.currentTimeMillis();
        int in = (int) ((now - time) * createTokenRate / 50);
        tokens = Math.min(size, tokens + in);
        System.out.println("now tokens: " + tokens);
        time = now;
        if (tokens > 0) {
            --tokens;
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 500; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (grant()) {
                        System.out.println("执行业务逻辑。");
                    } else {
                        System.out.println("限流。");
                    }
                }
            }).start();
        }
    }

}
